import 'package:flutter/material.dart';
import 'package:mysql1/mysql1.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TiDB Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: TiDBHomePage(),
    );
  }
}

class TiDBHomePage extends StatefulWidget {
  @override
  _TiDBHomePageState createState() => _TiDBHomePageState();
}

class _TiDBHomePageState extends State<TiDBHomePage> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _controller = TextEditingController();
  List<Map<String, dynamic>> _users = [];
  bool _loading = false;

  Future<MySqlConnection> _connectToTiDB() async {
    final settings = ConnectionSettings(
      host: 'gateway01.ap-southeast-1.prod.aws.tidbcloud.com', // 替换
      port: 4000,
      user: '3SZFNY6i1wPmRfJ.root',                      // 替换
      password: '0k9S7jjMh8z9mDaN',              // 替换
      db: 'test',                      // 替换
      useSSL: true,
    );
    return await MySqlConnection.connect(settings);
  }

  Future<void> _fetchUsers() async {
    setState(() => _loading = true);
    try {
      final conn = await _connectToTiDB();
      final results = await conn.query('SELECT name, email, created_at FROM test');
      _users = results
          .map((row) => {
                'name': row[0] as String,
                'email': row[1] as String,
                'created_at': row[2]?.toString() ?? '',
              })
          .toList();
      await conn.close();
    } catch (e) {
      print('Error: $e');
    }
    setState(() => _loading = false);
  }

  Future<void> _insertUser(String name, String email) async {
    setState(() => _loading = true);
    try {
      final conn = await _connectToTiDB();
      await conn.query('INSERT INTO test (name, email) VALUES (?, ?)', [name, email]);
      await conn.close();
      await _fetchUsers();
    } catch (e) {
      print('Insert error: $e');
    }
    _nameController.clear();
    _emailController.clear();
    setState(() => _loading = false);
  }

  @override
  void initState() {
    super.initState();
    _fetchUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("TiDB Flutter 示例")),
      body: Padding(
        padding: EdgeInsets.all(12),
        child: Column(
          children: [
            TextField(
              controller: _nameController,
              decoration: InputDecoration(labelText: "请输入用户名"),
            ),
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: "请输入邮箱"),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => _insertUser(_nameController.text, _emailController.text),
              child: Text("插入"),
            ),
            SizedBox(height: 20),
            _loading
                ? CircularProgressIndicator()
                : Expanded(
                    child: ListView(
                      children: _users.map((user) => ListTile(title: Text(user['name']), subtitle: Text('${user['email']}\n${user['created_at']}'))).toList(),
                    ),
                  ),
          ],
        ),
      ),
    );
  }
}
